<template>
  <div class="app-container">
    <el-form inline class="mb16">
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="range"
          type="daterange"
          value-format="YYYY-MM-DD"
          range-separator="至"
          start-placeholder="开始"
          end-placeholder="结束"
          :unlink-panels="true"
        />
      </el-form-item>
      <el-button type="primary" @click="load">查询</el-button>
      <el-button @click="reset">重置</el-button>
    </el-form>

    <div class="grid2 gap16">
      <div ref="cStatusRef" class="chart"></div>
      <div ref="cTrendRef"  class="chart"></div>
      <div ref="cAgingRef"  class="chart"></div>
      <div ref="cTypeRef"   class="chart"></div>
      <div ref="cPMRef"     class="chart"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'
import { fetchWoStatus, fetchWoType } from '@/api/sbtz/order'

const range = ref(null)

const cStatusRef = ref(null)
const cTrendRef  = ref(null)
const cAgingRef  = ref(null)
const cTypeRef   = ref(null)
const cPMRef     = ref(null)

let cStatus = null
let cTrend  = null
let cAging  = null
let cType   = null
let cPM     = null

function initCharts () {
  cStatus = echarts.init(cStatusRef.value)
  cTrend  = echarts.init(cTrendRef.value)
  cAging  = echarts.init(cAgingRef.value)
  cType   = echarts.init(cTypeRef.value)
  cPM     = echarts.init(cPMRef.value)
  window.addEventListener('resize', onResize)
}
function onResize () {
  cStatus && cStatus.resize()
  cTrend && cTrend.resize()
  cAging && cAging.resize()
  cType && cType.resize()
  cPM && cPM.resize()
}

async function load () {
  const params = {}
  if (range.value && range.value.length === 2) {
    params.beginTime = range.value[0]
    params.endTime = range.value[1]
  }

  const [sres, tres] = await Promise.all([
    fetchWoStatus(params),
    fetchWoType(params)
  ])

  renderStatus(sres.data || {})
  renderType(tres.data || {})
}

function reset () {
  range.value = null
  load()
}

function renderStatus (d) {
  // 1) 状态分布（环图）
  const statusData = (d.byStatus || []).map(x => ({ name: x.status, value: x.cnt }))
  cStatus.setOption({
    title: { text: '工单状态分类', left: 'center' },
    tooltip: { trigger: 'item' },
    legend: { bottom: 0 },
    series: [{ type: 'pie', radius: ['40%', '70%'], data: statusData }]
  })

  // 2) 创建 vs 完成（日趋势）
  const cr = d.dailyCreated || []
  const dn = d.dailyDone || []
  const days = Array.from(new Set([
    ...cr.map(x => x.day),
    ...dn.map(x => x.day)
  ])).sort()
  const y1 = days.map(day => (cr.find(x => x.day === day)?.cnt || 0))
  const y2 = days.map(day => (dn.find(x => x.day === day)?.cnt || 0))
  cTrend.setOption({
    title: { text: '创建 vs 完成（日）' },
    tooltip: { trigger: 'axis' },
    legend: { top: 0 },
    grid: { left: 40, right: 20, top: 40, bottom: 30, containLabel: true },
    xAxis: { type: 'category', data: days },
    yAxis: { type: 'value' },
    series: [
      { name: '创建', type: 'line', smooth: true, data: y1 },
      { name: '完成', type: 'line', smooth: true, data: y2 }
    ]
  })

  // 3) 未完成老化分桶
  cAging.setOption({
    title: { text: '未完成老化分布' },
    tooltip: {},
    xAxis: { type: 'category', data: (d.agingBuckets || []).map(x => x.bucket) },
    yAxis: { type: 'value' },
    series: [{ type: 'bar', data: (d.agingBuckets || []).map(x => x.cnt) }]
  })
}

function renderType (d) {
  // 4) 类型：数量 + 工时
  const rows = d.byType || []
  const types  = rows.map(r => r.type)
  const counts = rows.map(r => r.cnt)
  const hours  = rows.map(r => r.manHours)

  cType.setOption({
    title: { text: '工单类型统计（数量 & 工时）' },
    tooltip: { trigger: 'axis' },
    legend: { top: 0 },
    grid: { left: 50, right: 50, top: 40, bottom: 30, containLabel: true },
    xAxis: { type: 'category', data: types },
    yAxis: [
      { type: 'value', name: '数量' },
      { type: 'value', name: '工时(h)', position: 'right' }
    ],
    series: [
      { name: '数量', type: 'bar', data: counts },
      { name: '工时(h)', type: 'line', yAxisIndex: 1, smooth: true, data: hours }
    ]
  })

  // 5) PM 占比（数量口径）
  const pm = d.pmShare || {}
  const pctNum = pm.totalCount ? Math.round(pm.pmCount * 100 / pm.totalCount) : 0
  cPM.setOption({
    title: { text: 'PM 占比（数量）', left: 'center' },
    series: [{
      type: 'gauge',
      startAngle: 210, endAngle: -30, min: 0, max: 100,
      detail: { formatter: '{value}%' },
      data: [{ value: pctNum }]
    }]
  })
}

onMounted(async () => {
  await nextTick()
  initCharts()
  load()
})
onBeforeUnmount(() => {
  window.removeEventListener('resize', onResize)
  cStatus && cStatus.dispose()
  cTrend && cTrend.dispose()
  cAging && cAging.dispose()
  cType && cType.dispose()
  cPM && cPM.dispose()
})
</script>

<style scoped>
.grid2 { display: grid; grid-template-columns: 1fr 1fr; }
.gap16 { gap: 16px; }
.chart { width: 100%; height: 340px; }
.mb16 { margin-bottom: 16px; }
</style>
